/**
 * Copyright (c) 2018 软唐 All rights reserved.
 * <p>
 * https://www.softtown.cn
 * <p>
 * 版权所有，侵权必究！
 */

package com.softtown.modules.sys.service.impl;

import com.softtown.common.service.impl.BaseServiceImpl;
import com.softtown.common.utils.ConvertUtils;
import com.softtown.modules.oss.cloud.OSSFactory;
import com.softtown.modules.security.password.PasswordUtils;
import com.softtown.modules.security.user.SecurityUser;
import com.softtown.modules.sys.dao.SysNoticeDao;
import com.softtown.modules.sys.dao.SysUserDao;
import com.softtown.modules.sys.dto.RegistDTO;
import com.softtown.modules.sys.dto.SysUserDTO;
import com.softtown.modules.sys.dto.SysUserEmailDTO;
import com.softtown.modules.sys.dto.SysUserMobileDTO;
import com.softtown.modules.sys.entity.SysNoticeEntity;
import com.softtown.modules.sys.entity.SysUserEntity;
import com.softtown.modules.sys.enums.UserStatusEnum;
import com.softtown.modules.sys.service.SysRoleUserService;
import com.softtown.modules.sys.service.SysUserService;
import com.softtown.modules.sys.vo.SysUserVO;
import java.util.Objects;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 系统用户
 *
 * @author Ding Ya Yong
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    @Resource
    private SysRoleUserService sysRoleUserService;

    @Resource
    private SysNoticeDao sysNoticeDao;

    @Override
    public SysUserDTO getByUsername(String username) {
        SysUserEntity entity = baseDao.getByUsername(username);
        return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
    }

    @Override
    public SysUserDTO getByMobile(String mobile) {
        SysUserEntity entity = baseDao.getByMobile(mobile);
        return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserDTO dto) {
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserDTO dto) {
        SysUserEntity entity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);

        //密码加密
        if (StringUtils.isBlank(dto.getPassword())) {
            entity.setPassword(null);
        } else {
            String password = PasswordUtils.encode(entity.getPassword());
            entity.setPassword(password);
        }

        //更新用户
        updateById(entity);

        //更新角色用户关系
        sysRoleUserService.saveOrUpdate(entity.getId(), dto.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        //删除用户
        baseDao.deleteBatchIds(Arrays.asList(ids));

        //删除角色用户关系
        sysRoleUserService.deleteByUserIds(ids);
    }

    /**
     * 修改密码
     *
     * @param id newPassword
     * @return
     * @author Dingyayong
     * @date 2019/5/29 9:55
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(Long id, String newPassword) {
        newPassword = PasswordUtils.encode(newPassword);

        baseDao.updatePassword(id, newPassword);
    }

    /**
     * 用户注册
     *
     * @param dto
     * @return
     * @author Dingyayong
     * @date 2019/5/29 9:55
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(RegistDTO dto) {
        SysUserEntity entity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);
        //密码加密
        String password = PasswordUtils.encode(entity.getPassword());
        entity.setPassword(password);
        entity.setUsername(dto.getUsername());
        entity.setMobile(dto.getMobile());
        entity.setStatus(UserStatusEnum.ENABLED.value());
        insert(entity);
    }


    @Override
    public SysUserEntity getByUserId(Long id) {
        SysUserEntity sysUserEntity = baseDao.getByUserId(id);
        if (sysUserEntity.getHeadUrl() != null ) {
            sysUserEntity.setHeadUrl(Objects.requireNonNull(OSSFactory.build()).getHeadUrl(sysUserEntity.getHeadUrl()));
        }
        return sysUserEntity;
    }

    @Override
    public SysUserEntity getEntityByMobile(String mobile) {
        return baseDao.getEntityByMobile(mobile);
    }

    @Override
    public SysUserEntity getEntityByEmail(String email) {
        return baseDao.getEntityByEmail(email);
    }

    @Override
    public SysNoticeEntity findNotice() {
        return sysNoticeDao.findNotice();
    }

    /**
     * @param @param [sysUserMobileDTO]
     * @return @return void
     * @throws
     * @Title: updateMobileNumber
     * @Description: 用户解绑手机号Service实现方法
     * @author fuming
     * @date 2019/7/10 22:08
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMobileNumber(SysUserMobileDTO sysUserMobileDTO) {
        SysUserEntity sysUserEntity = ConvertUtils.sourceToTarget(sysUserMobileDTO, SysUserEntity.class);
        sysUserEntity.setId(sysUserMobileDTO.getId());
        sysUserEntity.setMobile(sysUserMobileDTO.getNewMobile());
        sysUserEntity.setUpdater(sysUserMobileDTO.getUpdater());
        sysUserEntity.setUpdateDate(new Date());
        sysUserEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
        sysUserEntity.setIsDeleted(0);
        baseDao.updateMobileNumber(sysUserEntity);
    }

    /**
     * @param @param [sysUserEmailDTO]
     * @return @return void
     * @throws
     * @Title: updateEmail
     * @Description: 用户解绑邮箱Service实现方法
     * @author fuming
     * @date 2019/7/12 19:37
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmail(SysUserEmailDTO sysUserEmailDTO) {
        SysUserEntity sysUserEntity = ConvertUtils.sourceToTarget(sysUserEmailDTO, SysUserEntity.class);
        sysUserEntity.setId(sysUserEmailDTO.getId());
        sysUserEntity.setMobile(sysUserEmailDTO.getNewEmail());
        sysUserEntity.setUpdater(sysUserEmailDTO.getUpdater());
        sysUserEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
        sysUserEntity.setUpdateDate(new Date());
        sysUserEntity.setIsDeleted(0);
        baseDao.updateEmail(sysUserEntity);
    }

    /**
     * @param @param [sysUserDTO]
     * @return @return void
     * @throws
     * @Title: updatePersonalInfo
     * @Description: 用户修改个人信息Service实现方法
     * @author fuming
     * @date 2019/7/12 19:37
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePersonalInfo(SysUserDTO sysUserDTO) {
        SysUserEntity sysUserEntity = ConvertUtils.sourceToTarget(sysUserDTO, SysUserEntity.class);
        sysUserEntity.setId(sysUserDTO.getId());
        sysUserEntity.setNickname(sysUserDTO.getNickname());
        if( sysUserDTO.getHeadUrl() != null){
            if(sysUserDTO.getHeadUrl().length()>0){
                sysUserEntity.setHeadUrl(sysUserDTO.getHeadUrl());
            }else {
                sysUserEntity.setHeadUrl(null);
            }

        }else {
            sysUserEntity.setHeadUrl(null);
        }
        sysUserEntity.setGender(sysUserDTO.getGender());
        sysUserEntity.setEmail(sysUserDTO.getEmail());
        sysUserEntity.setMobile(sysUserDTO.getMobile());
        sysUserEntity.setUpdater(sysUserDTO.getUpdater());
        sysUserEntity.setUpdateDate(new Date());
        sysUserEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
        sysUserEntity.setIsDeleted(0);
        baseDao.updatePersonalInfo(sysUserEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(SysUserEntity sysUserEntity) {
        baseDao.updateUserInfo(sysUserEntity);
    }

    /**
     * @param @param []
     * @return @return java.util.List<com.softtown.modules.sys.vo.SysUserVO>
     * @throws
     * @Title: getSysUserInfos
     * @Description: 查询所有用户信息Service实现方法
     * @author fuming
     * @date 2019/7/31 11:15
     */
    @Override
    public List<SysUserVO> getSysUserInfos() {
        List<SysUserEntity> userEntityList = baseDao.getSysUserInfos();
        return ConvertUtils.sourceToTarget(userEntityList, SysUserVO.class);
    }

    @Override
    public SysUserEntity getByUserIdOnLoginOut(Long id) {
        return baseDao.getByUserId(id);
    }

    @Override
    public SysUserEntity getUserByAccount(String userName) {
        return baseDao.getByUsername(userName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upadteUserInfoBySysUserDTO(SysUserDTO sysUserDTO) {
        SysUserEntity sysUserEntity = baseDao.getByUserId(sysUserDTO.getId());
        if (sysUserEntity != null) {
            sysUserEntity.setPassword(PasswordUtils.encode(sysUserDTO.getNewPassword()));
            sysUserEntity.setIsInitPassword(UserStatusEnum.ENABLED.value());
            sysUserEntity.setUpdater(SecurityUser.getUser().getId());
            sysUserEntity.setUpdateDate(new Date());
            sysUserEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
            baseDao.updateUserInfo(sysUserEntity);
        }
    }

    /**
     * 查询所有系统用户的邮箱账号
     *
     * @param
     * @return java.util.List<java.lang.String>
     * @Author fuming
     * @Date 2020/2/6 13:50
     */
    @Override
    public List<String> selectSysUserEmailList() {
        return baseDao.selectSysUserEmailList();
    }

    @Override
    public void changeUserLanguage(String language) {
        SysUserEntity sysUserEntity = baseDao.getByUserId(SecurityUser.getUserId());
        sysUserEntity.setUpdater(SecurityUser.getUserId());
        sysUserEntity.setUpdateDate(new Date());
        sysUserEntity.setLanguage(language);
        sysUserEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
        baseDao.updateUserInfo(sysUserEntity);
    }
}
